package com.qp.basics.common.service.impl;


import com.qp.basics.common.constant.Constants;
import com.qp.basics.common.domain.Company;
import com.qp.basics.common.domain.Dept;
import com.qp.basics.common.domain.UserInfo;
import com.qp.basics.common.repository.BaseRepository;
import com.qp.basics.common.service.UserInfoBaseService;
import com.qp.basics.common.utils.RedisUtils;
import com.qp.basics.common.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserInfoBaseServiceRedisImpl implements UserInfoBaseService {
    @Autowired
    RedisUtils redisUtils;
    @Autowired
    private BaseRepository<UserInfo, Long> userInfoRepository;

    @Override
    public UserInfo getById(Long id) {
        UserInfo userInfo = (UserInfo) redisUtils.hget(Constants.R_CLIENT_USERS, id.toString());
        if (userInfo == null) {
            userInfo = userInfoRepository.get(id, UserInfo.class);
            if (userInfo != null) {
                this.toRedis(userInfo);
            }
        }
        return userInfo;
    }

    @Override
    public UserInfo getByOpenid(String wxopenid) {
        UserInfo userInfo = null;
        if (!StringUtils.isEmpty(wxopenid) && !"undefined".equals(wxopenid)) {
            userInfo = userInfoRepository.queryUniqueResult("from UserInfo where openId='" + wxopenid + "'", null);
            if (userInfo != null) {
                this.toRedis(userInfo);
            }
        }
        return userInfo;
    }

    @Override
    public void deleteById(Long id) {
        redisUtils.hdel(Constants.R_CLIENT_USERS, id.toString());
    }

    @Override
    public void deleteByIds(Long[] ids) {
        redisUtils.hdel(Constants.R_CLIENT_USERS, ids);
    }

    @Override
    public void toRedis(UserInfo userInfo) {

        if (userInfo != null) {
            UserInfo userInfoNew = new UserInfo();
            BeanUtils.copyProperties(userInfo, userInfoNew,"company","dept");

            Company company = userInfo.getCompany();
            if (company != null) {
                Company c = new Company();
                c.setId(company.getId());
                c.setTitle(company.getTitle());
                userInfoNew.setCompany(c);
            }
            Dept dept = userInfo.getDept();
            if (dept != null) {
                Dept d = new Dept();
                d.setId(dept.getId());
                d.setName(dept.getName());
                userInfoNew.setDept(d);
            }
            redisUtils.hset(Constants.R_CLIENT_USERS, userInfoNew.getId().toString(), userInfoNew);
        }
    }
}
